from rest_framework import status
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response

from system.models import Permissions
from system.serializers.permissions import PermissionModelSerializer, PermissionsSerializer

class PermissionsModelVIewSet(ModelViewSet):
    """权限视图集"""
    queryset = Permissions.objects.all()
    serializer_class = PermissionModelSerializer

    def list(self, request, *args, **kwargs):
        serializer = self.get_serializer(self.get_queryset(), many=True)
        tree_dict = {}
        tree_data = []
        for item in serializer.data:
            tree_dict[item['id']] = item

        for key, item in tree_dict.items():
            if item.get('parent_id'):
                pid = item.get('parent_id')
                parent: dict = tree_dict.get(pid)
                parent.setdefault('children', []).append(item)
            else:
                tree_data.append(item)

        return Response(tree_data)


class PermissionAPIView(APIView):
    """权限APIView"""

    def get(self, request):
        queryset = Permissions.objects.all()
        print(queryset)
        serializer = PermissionsSerializer(queryset, many=True)
        print(type(serializer))
        print(serializer)
        print(serializer.data)
        # tree_dict = {}
        # for item in serializer.data:
        #     tree_dict[item.get('id')] = item
        # tree_data = self.data_convert_tree(tree_dict)
        # print(tree_data)
        # return Response(tree_data, status=status.HTTP_200_OK)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def data_convert_tree(self, data: dict):
        tree_data = []
        for key, value in data.items():
            pid = value.get('pid')
            if pid is not None:
                parent = data.get(pid)
                parent.setdefault('children', []).append(value)
            else:
                tree_data.append(value)
        return tree_data